package com.ktjy.t382.bank.controller;

import com.ktjy.t382.bank.entity.Account;
import com.ktjy.t382.bank.entity.Bank;
import com.ktjy.t382.bank.entity.vo.R;
import com.ktjy.t382.bank.service.impl.BankServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
public class BankController {
    @Resource
    BankServiceImpl bankService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final long TOKEN_EXPIRE_TIME = 30 * 60; // token有效期半小时

    @RequestMapping("/login")
    public R login(@RequestBody Account account) {
        Account result = bankService.login(account);
        if (result != null) {
            // 生成token
            String token = UUID.randomUUID().toString();
            //将用户信息存入Redis，设置过期时间
            String redisKey = "token:" + token;
            redisTemplate.opsForValue().set(redisKey, result, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
            //构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("userInfo", result);
            data.put("token", token);
            return R.ok(data);
        }
        return R.fail("账号或密码错误");
    }

    @PostMapping("/logout")
    public R logout(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String redisKey = "token:" + token;
            // 从Redis中删除token
            redisTemplate.delete(redisKey);
            return R.ok("退出登录成功");
        }
        return R.fail("退出登录失败");
    }

    @GetMapping("/balance")
    public R balance(@RequestParam String cardno) {
        Account account = bankService.checkBalance(cardno);
        if (account != null) {
            return R.ok(account);
        }
        return R.fail("查询余额失败!");
    }

    /**
     * 分页功能
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/page")
    public R selectPage(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String cardno,
            @RequestParam String startTime,
            @RequestParam String endTime) {
        try {
            Bank bank = new Bank();
            bank.setCardno(cardno);
            List<Bank> list = bankService.findPageVo(bank, cardno, startTime, endTime, pageNo, pageSize);
            return R.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("查询异常: " + e.getMessage());
            return R.fail("获取交易记录失败: " + e.getMessage());
        }
    }

    /**
     * 转账功能
     *
     * @param cardno     收款卡号
     * @param balance    转账金额
     * @param fromCardno 转出卡号
     * @param remark     备注
     * @return 转账结果
     */
    @ResponseBody
    @RequestMapping(value = "/transfer", method = {RequestMethod.POST, RequestMethod.GET})
    public R transfer(
            @RequestParam String cardno,  // 收款卡号
            @RequestParam String balance, // 转账金额
            @RequestParam String fromCardno, // 转出卡号
            @RequestParam String remark) {
        try {
            // 金额格式处理，移除可能的非数字字符
            String cleanedBalance = balance.replaceAll("[^\\d.]", "");
            Double amount = Double.parseDouble(cleanedBalance);

            // 参数验证
            if (cardno == null || fromCardno == null || amount == null || amount <= 0) {
                return R.fail("参数不完整或金额无效");
            }

            // 确保卡号格式正确（去除可能的空格）
            fromCardno = fromCardno.trim();
            cardno = cardno.trim();


            // 先检查账户是否存在
            Account fromAccount = bankService.checkBalance(fromCardno);

            if (fromAccount == null) {
                return R.fail("转出账户不存在");
            }

            Account toAccount = bankService.checkBalance(cardno);

            if (toAccount == null) {
                return R.fail("收款账户不存在");
            }

            // 调用服务层执行转账
            Map<String, Object> transferResult = bankService.transfer(
                    fromCardno, cardno, amount, remark);

            if ((Boolean) transferResult.get("success")) {
                return R.ok(transferResult.get("data"));
            } else {
                return R.fail((String) transferResult.get("message"));
            }
        } catch (NumberFormatException e) {
            System.out.println("金额格式转换错误: " + e.getMessage() + ", 原始值: " + balance);
            return R.fail("转账金额格式不正确，请输入有效的数字");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转账处理异常: " + e.getMessage());
            return R.fail("转账失败：" + e.getMessage());
        }
    }

    /**
     * 确认密码功能
     *
     * @param account
     * @return
     */
    @PostMapping("/confirmPassword")
    public R confirmPassword(@RequestBody Account account) {
        int count = bankService.confirmPassword(account);
        if (count > 0) {
            return R.ok();
        }
        return R.fail("当前密码不正确");
    }

    /**
     * 修改密码功能
     *
     * @param account
     * @return
     */
    @ResponseBody
    @PostMapping("/changePassword")
    public R changePassword(@RequestBody Account account) {
        int count = bankService.changePassword(account);
        if (count > 0) {
            return R.ok();
        }
        return R.fail("密码修改失败");
    }
}
